package com.yg.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yg.config.FilePathConfig;
import com.yg.config.result.R;
import com.yg.config.result.ResultCode;
import com.yg.entity.readAndWriteTemplates.TeachingMeetRead;
import com.yg.entity.singleEntity.TeachingMeet;
import com.yg.mapper.TeachingMeetMapper;
import com.yg.service.TeachingMeetService;
import com.yg.utils.DateValidationUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 对应sheet11，此表是教师参加教学会议表 服务实现类
 * </p>
 *
 * @author YingGu
 * @since 2020-11-04
 */
@Service
public class TeachingMeetServiceImpl extends ServiceImpl<TeachingMeetMapper, TeachingMeet> implements TeachingMeetService {

    @Autowired
    TeachingMeetMapper teachingMeetMapper;
    @Autowired
    FilePathConfig filePathConfig;

    /**
     * excel写入
     *
     * @param fileInputStream
     * @return
     */
    @Transactional
    @Override
    public R readExcel(FileInputStream fileInputStream) {
        List<TeachingMeet> teachingMeets = new ArrayList<>();
        //创建R
        R r = R.getR();
        r.setCode(ResultCode.SUCCESS);
        //存储错误信息
        List<String> errorList = new ArrayList<>();

        //读取excel(匿名内部类解决传参问题)
        EasyExcel.read(fileInputStream, TeachingMeetRead.class, new AnalysisEventListener<TeachingMeetRead>() {
            //每行执行
            @Override
            public void invoke(TeachingMeetRead teachingMeetRead, AnalysisContext analysisContext) {
                //创建数据库对应实体类
                TeachingMeet teachingMeet = new TeachingMeet();
                teachingMeetRead.setTime(DateValidationUtil.dateValidation(teachingMeetRead.getTime(),"yyyy.MM.dd"));
                //将表格bean复制到对应数据库bean
                BeanUtils.copyProperties(teachingMeetRead, teachingMeet);

                //添加进List
                teachingMeets.add(teachingMeet);
            }

            //所有行读完执行
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                if (r.getCode() == ResultCode.SUCCESS) {
                    //向数据库插入数据
                    saveData();
                } else {
                    r.data("errorMsg", errorList);
                }
            }

            /**
             * 数据类型转换异常处理
             * @param exception
             * @param context
             * @throws Exception
             */
            @Override
            public void onException(Exception exception, AnalysisContext context) throws Exception {
                if (exception instanceof ExcelDataConvertException) {
                    ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;

                    //向errorList中添加信息
                    r.code(ResultCode.ERROR);
                    System.out.println("行：" + excelDataConvertException.getRowIndex() + "列" + excelDataConvertException.getColumnIndex());
                    errorList.add("行：" + excelDataConvertException.getRowIndex() + "列" + excelDataConvertException.getColumnIndex());
//                    LOGGER.error("第{}行，第{}列解析异常", excelDataConvertException.getRowIndex(),
//                            excelDataConvertException.getColumnIndex());
                }
            }

            //存数据库操作
            private void saveData() {
                for (TeachingMeet teachingMeet : teachingMeets) {
                    teachingMeetMapper.insert(teachingMeet);
                    System.out.println(teachingMeet);
                }
                r.code(ResultCode.SUCCESS).message("插入成功");
            }
        }).headRowNumber(6).sheet().doRead();

        return r;
    }

    /**
     * excel写出
     *
     * @return
     */
    @Transactional
    @Override
    public R writeExcel(TeachingMeet teachingMeet, HttpServletResponse response) {
        List<TeachingMeet> teachingMeets = new ArrayList<>();
        if (teachingMeet == null) {
            //从数据库中查询对应表格
            teachingMeets = teachingMeetMapper.selectList(null);
        } else {
            QueryWrapper<TeachingMeet> teachingMeetQueryWrapper = new QueryWrapper<>();
            if (teachingMeet.getName() != null) {
                teachingMeetQueryWrapper.like("name", teachingMeet.getName());
            }
            teachingMeets = teachingMeetMapper.selectList(teachingMeetQueryWrapper);
        }
        //创建list存放导出bean
        List<TeachingMeetRead> teachingMeetReads = new ArrayList<>();

        //将数据库对应的bean复制给导出表格bean
        for (int i = 0; i < teachingMeets.size(); i++) {
            TeachingMeetRead teachingMeetRead = new TeachingMeetRead();
            BeanUtils.copyProperties(teachingMeets.get(i), teachingMeetRead);
            //设置序号
            teachingMeetRead.setNum(i + 1);
            teachingMeetReads.add(teachingMeetRead);
        }

        //导出(匿名内部类SheetWriteHandler)
        try {
            String fileName = URLEncoder.encode("sheet11教师会议", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream()).withTemplate(filePathConfig.writeExcelFilePath + "sheet11Template.xlsx").registerWriteHandler(new SheetWriteHandler() {
                @Override
                public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

                }

                @Override
                public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

                }
            }).sheet().doFill(teachingMeetReads);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.OK();
    }

    /**
     * 查询所有信息
     *
     * @return
     */
    @Override
    public R selectAllTeachMeet(String current, String limit) {
        Page<TeachingMeet> teachingMeetPage = new Page<>(Integer.valueOf(current), Integer.valueOf(limit));
        IPage<TeachingMeet> teachingMeetIPage = teachingMeetMapper.selectPage(teachingMeetPage, null);
        List<TeachingMeet> records = teachingMeetIPage.getRecords();
        records.forEach(System.out::println);
        System.out.println("总页数" + teachingMeetIPage.getPages());
        return R.OK().data("list", records).data("list", records).data("pages", teachingMeetIPage.getPages()).data("total", teachingMeetIPage.getTotal());
    }

    /**
     * 条件查询
     *
     * @param s
     * @return
     */
    @Override
    public R conditionalQuery(String current, String limit, TeachingMeetRead teachingMeetRead) {
        Page<TeachingMeetRead> teachingMeetReadPage = new Page<>(Integer.valueOf(current), Integer.valueOf(limit));
        IPage<TeachingMeetRead> teachingMeetReadIPage = teachingMeetMapper.teachingMeetConditionalQuery(teachingMeetReadPage, teachingMeetRead);
        List<TeachingMeetRead> records = teachingMeetReadIPage.getRecords();
        return records.size() != 0 ? R.OK().data("list", records).data("pages", teachingMeetReadIPage.getPages()).data("total", teachingMeetReadIPage.getTotal()) : R.OK().message("您所查询的信息不存在").data("list", records).data("pages", teachingMeetReadIPage.getPages()).data("total", teachingMeetReadIPage.getTotal());
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public R deleteTeachingMeetById(TeachingMeet teachingMeet) {
        int id1 = teachingMeetMapper.deleteById(teachingMeet.getId());
        return id1 == 1 ? R.OK().message("删除成功") : R.ERROR().code(ResultCode.DELETEERROR).message("删除失败");
    }

    /**
     * 更新信息
     *
     * @param s
     * @return
     */
    @Override
    public R updateTeachingMeet(TeachingMeetRead teachingMeetRead) {
        TeachingMeet teachingMeet = new TeachingMeet();
        teachingMeetRead.setTime(DateValidationUtil.dateValidation(teachingMeetRead.getTime(),"yyyy.MM.dd"));
        //复制属性
        BeanUtils.copyProperties(teachingMeetRead, teachingMeet);
        //返回数值1
        int teachingMeetupdate = teachingMeetMapper.updateById(teachingMeet);
        return teachingMeetupdate == 1 ? R.OK().message(teachingMeetRead.getId() + teachingMeetRead.getName() + "修改成功") : R.ERROR().code(ResultCode.UPDATEERROR).message(teachingMeetRead.getId() + teachingMeetRead.getName() + "修改失败");
    }

    /**
     * 添加会议
     *
     * @param s
     * @return
     */
    @Override
    public R insertTeachingMeet(TeachingMeet teachingMeet) {
        teachingMeet.setTime(DateValidationUtil.dateValidation(teachingMeet.getTime(),"yyyy.MM.dd"));
        int insert = teachingMeetMapper.insert(teachingMeet);
        return insert == 1 ? R.OK().message(teachingMeet.getId() + teachingMeet.getName() + "添加成功") : R.ERROR().code(ResultCode.UPDATEERROR).message(teachingMeet.getId() + teachingMeet.getName() + "添加失败");
    }
}
